package com.huayi.datagovernance.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huayi.datagovernance.dao.master.IscUserLocextMapper;
import com.huayi.datagovernance.entity.IscUserLocext;
import com.huayi.datagovernance.service.AppService;
import com.huayi.datagovernance.utils.JwtUtils;
import com.huayi.datagovernance.vo.ResponseResult;
import common.parent.system.tokenauth.DecodeTokenInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * App用户服务-接口实现
 * @version 1.0
 * @date 2021/4/21 15:36
 */
@Service
@Slf4j
public class AppServiceImpl implements AppService {

    @Resource
    private IscUserLocextMapper userLocextMapper;

    @Override
    public ResponseResult<JSONObject> login(JSONObject jsonObject) {
        log.info("login参数：" + jsonObject.toJSONString());
        try {
            if (StrUtil.isBlankIfStr(jsonObject.get("appAccount")) || StrUtil.isBlankIfStr(jsonObject.get("orgNo"))) {
                //返回入参，方便排查
                return ResponseResult.failed(jsonObject, "尚未登录易作业！");
            }
            //根据app帐号查询用户信息
            IscUserLocext user = userLocextMapper.findByAppAccount(jsonObject.getString("appAccount"));
            if (user == null) {
                return ResponseResult.failed(jsonObject, "用户不存在！");
            }
            //生成token
            String token = JwtUtils.createToken(user);
            DecodeTokenInfoDTO dto = JwtUtils.getAllDecodeTokenInfo(token);
            JSONObject data = JSON.parseObject(JSON.toJSONString(dto), JSONObject.class);
            data.put("token", token);
            data.put("tokenExpiresAt", String.valueOf(System.currentTimeMillis() + JwtUtils.getLifeTimeSeven()));// 过期时间=当前时间戳+token有效期
            return ResponseResult.success(data);
        } catch (Exception e) {
            log.error("登录失败", e);
            return ResponseResult.failed(jsonObject, e.getMessage());
        }
    }
}
